package com.netty.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 模拟bio的阻塞模型
 * 6666端口启动服务
 * telnet 127.0.0.1 6666模拟client端去请求server端，每个client请求都会新开一个thread去处理，而且处理的过程会阻塞
 * */
public class BioServer {

    public static void main(String[] args) throws Exception {

        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动成功");
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        while (true) {
            //连接成功就得到一个socket
            Socket socket = serverSocket.accept();

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        handle(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }


    public static void handle(Socket socket) throws IOException {
        System.out.println("线程id:" + Thread.currentThread().getId() + "线程名称:" + Thread.currentThread().getName());
        byte[] bytes = new byte[1024];
        InputStream inputStream = socket.getInputStream();
        try {
            while (true) {
                //会阻塞
                int read = inputStream.read(bytes);
                if (read != -1) {
                    //输出客户端发送的数据
                    System.out.println("线程" + Thread.currentThread().getName() + "输出:" +new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭client连接");
            inputStream.close();
            socket.close();
        }
    }

}
